package main

import (
	"consul/pb"
	"context"
	"fmt"
	"github.com/hashicorp/consul/api"
	"google.golang.org/grpc"
	"net"
)

// Children 定义类
type Children struct {
}

// TestConsul 绑定类方法，实现接口
// TestConsul(context.Context, p *pb.Person) (*pb.Person, error)
func (args *Children) TestConsul(ctx context.Context, p *pb.Person) (*pb.Person, error) {
	p.Name = "welcome " + p.Name
	return p, nil
}
func main() {
	//把grpc服务，注册到consul
	// 1.初始化consul配置
	consulConfig := api.DefaultConfig()
	// 2. 创建consul对象
	consulClient, err := api.NewClient(consulConfig)
	if err != nil {
		fmt.Println("api.NewClient err:", err)
		return
	}

	// 3. 告诉consul，即将注册的服务的配置信息
	reg := api.AgentServiceRegistration{
		ID:      "CC1010",
		Tags:    []string{"grpc", "consul"},
		Name:    "grpc And Consul",
		Address: "127.0.0.1",
		Port:    8080,
		Check: &api.AgentServiceCheck{
			CheckID:  "consul grpc test",
			TCP:      "127.0.0.1:8080",
			Timeout:  "1s",
			Interval: "5s",
		},
	}

	//4. 注册grpc服务到consul上
	consulClient.Agent().ServiceRegister(&reg)

	/*
	   以下是grpc服务远程调用
	*/

	// 1.初始化grpc对象
	grpcServer := grpc.NewServer()

	// 2.注册服务
	pb.RegisterHelloServer(grpcServer, new(Children))

	// 3.设置监听,指定IP、port
	listener, err := net.Listen("tcp", "127.0.0.1:8080")
	if err != nil {
		fmt.Println("listen err:", err)
	}
	defer listener.Close()

	//4. 启动服务

	grpcServer.Serve(listener)

}
